package cn.com.utt.common.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.im4java.core.ConvertCmd;
import org.im4java.core.IM4JavaException;
import org.im4java.core.IMOperation;
import org.im4java.core.IdentifyCmd;
import org.im4java.process.ArrayListOutputConsumer;
import org.im4java.process.StandardStream;

public class GraphicsMagickUtil {
	/**
	 * * 获得图片文件大小[小技巧来获得图片大小] * * @param filePath * 文件路径 *
	 * 
	 * @return 文件大小
	 */
	public static int getSize(String imagePath) {
		int size = 0;
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(imagePath);
			size = inputStream.available();
			inputStream.close();
			inputStream = null;
		} catch (FileNotFoundException e) {
			size = 0;
			e.printStackTrace();
		} catch (IOException e) {
			size = 0;
			e.printStackTrace();
		} finally {
			// 可能异常为关闭输入流,所以需要关闭输入流
			if (null != inputStream) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				inputStream = null;
			}
		}
		return size;
	}
	
	// 按指定宽度等比缩放
	public static void scaleImage(int maxWidth, int maxHeight,
			String originPath, String savePath) throws Exception {
			int width = getWidth(originPath);
			int height = getHeight(originPath);
			// 由于页面宽度是固定的，所以图片是否缩放由宽度决定
			// 图片原始宽度小于指定的宽度不用处理。
			if (width > maxWidth) {
				double ratio = width / maxWidth;
				height = (int) (height / ratio);
				width = maxWidth;
			}
			IMOperation op = new IMOperation();
			ConvertCmd convert = new ConvertCmd(true);
			String osName = System.getProperty("os.name").toLowerCase();
			if (osName.indexOf("win") != -1) {
				// linux下不要设置此值，不然会报错
				convert.setSearchPath("C://Program Files//GraphicsMagick-1.3.21-Q8");
			}else{
				convert.setSearchPath("/usr/local/bin");	
			}
			int size = getSize(originPath);
			System.out.println("img size:"+size);
			op.addImage();
			if (size >= 409600) {
				op.addRawArgs("-quality", "40");
			}
			if (size >= 204800) {
				op.addRawArgs("-quality", "60");
			} else {
				op.addRawArgs("-quality", "75");
			}
			System.out.println(width+","+height);
			op.addRawArgs("-sample", width + "x" + height + "^");
			// remove exif info
			op.p_profile("*");
			op.addImage();
			convert.run(op, originPath, savePath);
	}

	// 指定宽度和高度缩放
	public static void zoomImage(int width, int height, String originPath,
			String savePath) throws Exception {
		IMOperation op = new IMOperation();
		ConvertCmd convert = new ConvertCmd(true);
		String osName = System.getProperty("os.name").toLowerCase();
		if (osName.indexOf("win") != -1) {
			// linux下不要设置此值，不然会报错
			convert.setSearchPath("C://Program Files//GraphicsMagick-1.3.21-Q8");
		}else{
			convert.setSearchPath("/usr/local/bin");	
		}
		int size = getSize(originPath);
		op.addImage();
		System.out.println("image size");
		if (size >= 409600) {
			op.addRawArgs("-quality", "40");
		}
		if (size >= 204800) {
			op.addRawArgs("-quality", "60");
		} else {
			op.addRawArgs("-quality", "75");
		}
		op.addRawArgs("-sample", width + "x" + height + "^");
		op.p_profile("*");
		op.addImage();
		convert.run(op, originPath, savePath);
	}

	/*
	 *cmd: gm composite -gravity northwest -geometry +63+27 qrcode.jpg wx_mark.png dest.png
	 */
	public static void composite(String markImgPath, String srcImagePath,
			String targetImgPath) throws IOException, InterruptedException,
			IM4JavaException {
		IMOperation op = new IMOperation();
		op.addImage(markImgPath);
		/*op.draw("image Over " + 560 + "," + 27 + " " + 258 + "," + 258 + " "
				+ src2ImagePath);*/
		op.draw("image Over " + 63 + "," + 27 + " " + 258 + "," + 258 + " "
				+ srcImagePath);
		// op.draw("image Over x,y x1,y1 XX.img.jpg"); x,y 是图片左上角的坐标，x1，y1则是这个图片拼接到原图的大小
		op.addImage(targetImgPath);
		// IM4JAVA是同时支持ImageMagick和GraphicsMagick的，如果为true则使用GM，如果为false支持IM。
		ConvertCmd convert = new ConvertCmd(true);
		String osName = System.getProperty("os.name").toLowerCase();
		if (osName.indexOf("win") != -1) {
			// linux下不要设置此值，不然会报错
			convert.setSearchPath("C://Program Files//GraphicsMagick-1.3.21-Q8");
		}else{
			convert.setSearchPath("/usr/local/bin");	
		}
		convert.setErrorConsumer(StandardStream.STDERR);
		convert.run(op);
	}
	
	public static void composite(String markImgPath, String srcImagePath,
			String targetImgPath,String keyword) throws IOException, InterruptedException,
			IM4JavaException {
		composite(markImgPath, srcImagePath, targetImgPath);
		IMOperation op = new IMOperation();
		String txt = "关注公众号回复\""+keyword+"\"认证上网";
		System.out.println("txt:"+txt);
		op.font("/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc").pointsize(15).fill("black").draw("text 78,340 '" + txt + "'").quality(90.0);
		op.addImage();
		op.addImage();
		String osName = System.getProperty("os.name").toLowerCase();
		ConvertCmd cmd = new ConvertCmd(true);
		if (osName.indexOf("win") != -1) {
			// linux下不要设置此值，不然会报错
			cmd.setSearchPath("C://Program Files//GraphicsMagick-1.3.21-Q8");
		}else{
			cmd.setSearchPath("/usr/local/bin");	
		}
		try {
			cmd.run(op, targetImgPath, targetImgPath);
			System.out.println("over");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static int getWidth(String imagePath) {
	    int line = 0;
	    try {
	        IMOperation op = new IMOperation();
	        op.format("%w"); // 设置获取宽度参数
	        op.addImage(1);
	        IdentifyCmd identifyCmd = new IdentifyCmd(true);
	        ArrayListOutputConsumer output = new ArrayListOutputConsumer();
	    	String osName = System.getProperty("os.name").toLowerCase();
	    	if (osName.indexOf("win") != -1) {
				// linux下不要设置此值，不然会报错
	    		identifyCmd.setSearchPath("C://Program Files//GraphicsMagick-1.3.21-Q8");
			}else{
				identifyCmd.setSearchPath("/usr/local/bin");	
			}     
	        identifyCmd.setOutputConsumer(output);
	        identifyCmd.run(op, imagePath);
	        ArrayList<String> cmdOutput = output.getOutput();
	        assert cmdOutput.size() == 1;
	        String out = cmdOutput.get(0);
	        if (out.length()>4){
	        	//如果是动态图可能会出现类似401401401401401这样的尺寸
	        	line = Integer.parseInt(out.substring(0, 3));
	        	System.out.println(line);
	        }else{
	        	line = Integer.parseInt(out);
	        }
	    } catch (Exception e) {
	    	e.printStackTrace();
	        line = 0;
	        System.out.println("运行指令出错!");
	    }
	    return line;
	}

	/**
	 * 获得图片的高度
	 * 
	 * @param imagePath
	 *            文件路径
	 * @return 图片高度
	 */
	public static int getHeight(String imagePath) {
	    int line = 0;
	    try {
	        IMOperation op = new IMOperation();
	        op.format("%h"); // 设置获取高度参数
	        op.addImage(1);
	        IdentifyCmd identifyCmd = new IdentifyCmd(true);
	        ArrayListOutputConsumer output = new ArrayListOutputConsumer();
	    	String osName = System.getProperty("os.name").toLowerCase();
	    	if (osName.indexOf("win") != -1) {
				// linux下不要设置此值，不然会报错
	    		identifyCmd.setSearchPath("C://Program Files//GraphicsMagick-1.3.21-Q8");
			}else{
				identifyCmd.setSearchPath("/usr/local/bin");	
			}  
	        identifyCmd.setOutputConsumer(output);
	        identifyCmd.run(op, imagePath);
	        ArrayList<String> cmdOutput = output.getOutput();
	        assert cmdOutput.size() == 1;
	        String out = cmdOutput.get(0);
	        if (out.length()>4){
	        	line = Integer.parseInt(out.substring(0, 3));
	        	System.out.println(line);
	        }else{
	        	line = Integer.parseInt(out);
	        }
	    } catch (Exception e) {
	    	e.printStackTrace();
	        line = 0;
	        System.out.println("运行指令出错!"+e.toString());
	    }
	    return line;
	}


	public static void main(String[] args) {
		/*try {
			composite("D://wx_mark.png","D://qrcode_for_gh_798a0146fc67_258.jpg", 
					"D://test.png");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IM4JavaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		/*
		System.out.println(getHeight("D://qrcode_for_gh_798a0146fc67_430.jpg"));
		System.out.println(getWidth("D://qrcode_for_gh_798a0146fc67_430.jpg"));
		int height = getHeight("D://qrcode_for_gh_798a0146fc67_430.jpg");
		int width = getWidth("D://qrcode_for_gh_798a0146fc67_430.jpg");
		if(height!=258 || width!=258){
			try {
				zoomImage(258, 258, "D://qrcode_for_gh_798a0146fc67_430.jpg", "D://target123.png");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		*/
		String srcPath = "d:/wx_mark.png";
		IMOperation op = new IMOperation();
		//GMOperation op = new GMOperation();

		String txt = "关注公众号回复\"WIFI\"认证上网";
		byte[] bs = txt.getBytes();
		   //用新的字符编码生成字符串
		String text="";
		try {
			text = new String(bs, "GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		op.font("微软雅黑").pointsize(18).fill("#BCBFC8")
				.draw("text 90,340 '" + text + "'").quality(90.0);
		op.addImage();

		op.addImage();

		String osName = System.getProperty("os.name").toLowerCase();

		ConvertCmd cmd = new ConvertCmd(true);

		if (osName.indexOf("win") != -1) {

			// linux下不要设置此值，不然会报错

			cmd.setSearchPath("C://Program Files//GraphicsMagick-1.3.21-Q8");

		}

		try {

			cmd.run(op, srcPath, "d:/2.jpg");
			System.out.println("over");
		} catch (Exception e) {

			e.printStackTrace();

		}
	}

}
